package com.training1.core.common.log;

import java.util.Arrays;
import java.util.List;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import com.training1.core.common.utils.IdGen;

/**
 * 批处理记录
 * @author hl
 *
 */
@Aspect
@Component
public class BatchLog {

	private static final Logger log = LoggerFactory.getLogger("batch");
	
	@Around("@annotation(org.springframework.scheduling.annotation.Scheduled)")
	public Object doAround(ProceedingJoinPoint pjd) throws Throwable {
		String methodName = pjd.toShortString();
		MDC.put("user", IdGen.uuid().substring(IdGen.uuid().length()/2, IdGen.uuid().length()));
		List<Object> args = Arrays.asList(pjd.getArgs());
		long now = System.currentTimeMillis();
		Object ret = null;
		try{
			if(args.size()>0){
				log.info("批处理{}开始执行,参数为{}",methodName,args);
				ret = pjd.proceed(pjd.getArgs());
			}else{
				log.info("批处理{}开始执行",methodName);
				ret = pjd.proceed();
			}
		}catch(Throwable e){
			long cost = System.currentTimeMillis()-now;
			log.error("执行批处理{}出错,参数为{},错误信息:{},耗时{}毫秒", methodName,args,e.getMessage(),cost);
			throw e;
		}
		long cost = System.currentTimeMillis()-now;
		log.info("执行{}完成，入参为{},返回{},执行耗时{}毫秒", methodName,args,ret,cost,ret);
		return ret;
	}
	
}
